const fs = require('fs');
const yaml = require('js-yaml');
const { getFilePath } = require('./util');

function deepMerge(target, source) {
  for (let key in source) {
    if (
      source[key] &&
      typeof source[key] === 'object' &&
      !Array.isArray(source[key]) &&
      target[key] &&
      typeof target[key] === 'object'
    ) {
      target[key] = deepMerge(target[key], source[key]);
    } else {
      target[key] = source[key];
    }
  }
  return target;
}

/**
 * 加载环境变量配置
 * 配置文件优先级
 * 优先级从高到低
 * 1. local.yaml
 * 2. config.yaml
 * 3. config.${env}.yaml
 **/
function loadEnv() {
  const env = process.env.NODE_ENV || 'development';
  const envConfigFile = env === 'production' ? '/config/config.prod.yaml' : '/config/config.dev.yaml';
  try {
    // 读取 config.yaml 和 config.${env}.yaml
    const envConfigContent = fs.readFileSync(getFilePath(envConfigFile), 'utf8');
    const configContent = fs.readFileSync(getFilePath('/config/config.yaml'), 'utf8');
    const envConfig = yaml.load(envConfigContent) || {};
    const config = yaml.load(configContent) || {};
    const mergedConfig = deepMerge(config, envConfig);
    // 读取 local.yaml
    const localContent = fs.readFileSync(getFilePath('/config/local.yaml'), 'utf8');
    const localConfig = yaml.load(localContent) || {};
    const allConfig = deepMerge(mergedConfig, localConfig);
    global.__config = mergedConfig;
    console.log(`已加载 ${env} 环境配置与默认环境配置`, allConfig, '\n');
    return allConfig;
  } catch (e) {
    console.error('处理 YAML 时出错:', e.message);
    console.error(e.stack);
    return null;
  }
}

module.exports = loadEnv;
